package com.example.demo.component;

import com.example.demo.common.ApplicationVariable;
import com.example.demo.common.CommonResult;
import com.example.demo.common.SessionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-08-24
 * Time: 9:58
 */
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.warn("已拦截：" + request.getRequestURI());
        //业务逻辑
        if (SessionUtils.getUser(request) != null) {
            return true;//用户登录
        }
        response.setContentType("application/json; charset=utf8");
        response.getWriter().write(objectMapper.writeValueAsString(CommonResult.fail(302, "/blog_login.html")));
        response.sendRedirect("/blog_login.html");
        return false;
    }
}
